/*******************************************************************
 *   > File Name: cmd_parse.c
 *   > Author: fly
 *   > Mail: XXXXXXXX@icode.com
 *   > Create Time: 2020年06月16日 星期二 23时11分23秒
 ******************************************************************/
#include "cmd_parse.h"
#include "stdio.h"
#include "printf.h"
#include "string.h"
//#include <stdio.h>
//#include <string.h>

static CMD_PARSE CMD_TABLE[] = {
    {"help",        "list all cmd info"     ,printf_help},
    {"led_on",      "turn on led"           ,led_on_process},
    {"led_off",     "turn off led"          ,led_off_process},

    //{NULL,          NULL,                   NULL},
};

void printf_help(void)
{
    int cmd_at;
    printf("My shell commands:\n");
    for(cmd_at = 0; cmd_at <sizeof(CMD_TABLE)/sizeof(CMD_PARSE);cmd_at++ )
    {
        printf("CMD_TAB[%d]: %s-->%s\n", \
                cmd_at, CMD_TABLE[cmd_at].cmd_type, CMD_TABLE[cmd_at].cmd_help);
    }
}

void led_on_process(void){
    printf("%s\n",__FUNCTION__);
}

void led_off_process(void){
    printf("%s\n",__FUNCTION__);
}

int command_matching(char *cmd_type)
{
    int cmd_at = 0;
    int cmd_match_flag = 0;
    int type_num = NR(CMD_TABLE);

    for(cmd_at = 0; cmd_at < type_num; cmd_at++)
    {
        if(!strcmp(CMD_TABLE[cmd_at].cmd_type, cmd_type))
        {
            cmd_match_flag = 1;
            break;
        }
    }

    if(1 == cmd_match_flag)
    {
        cmd_match_flag = 0;
        CMD_TABLE[cmd_at].fun_ptr();
    }else{
        puts("no match cmd .\n");return -1;
    }

    return 1;
}

void cmd_line(void)
{
    char str[CMD_LINE_STR_LENGTH]={0};
	puts("This is a simple shell.\n");
    while(1)
    {
        puts("fly#");
        memset(str, 0, sizeof(str));
        //scanf("%s", str);
		gets(str);
		puts("get stirng:");
		printf("%s\n\r", str);
        command_matching(str);
    }
}

#ifdef CMD_PARSE_DEBUG
int main(int argc, char* argv[])
{
    cmd_line();
    return 0;
}
#endif /* CMD_PARSE_DEBUG */
